package org.gy.T10.t5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSystem {
    private static final int TOTAL_TICKETS = 10; // 总票数
    private int ticketsRemaining = TOTAL_TICKETS; // 剩余票数
    private final Lock lock = new ReentrantLock(); // 创建一个锁对象

    public void buyTicket() {
        lock.lock(); // 获取锁
        try {
            if (ticketsRemaining > 0) {
                System.out.println(Thread.currentThread().getName() + " 已经购买了一张票，剩余票数: " + --ticketsRemaining);
            } else {
                System.out.println(Thread.currentThread().getName() + " 不能买票了，票已经卖完了.");
            }
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    public static void main(String[] args) {
        TicketSystem ticketSystem = new TicketSystem();

        // 创建并启动100个线程
        for (int i = 0; i < 11; i++) {
            new Thread(ticketSystem::buyTicket, "Thread-" + (i + 1)).start();
        }

//        // 创建并启动10个线程
//        for (int i = 0; i < 10; i++) {
//            new Thread(ticketSystem::buyTicket, "Thread-" + (i + 1)).start();
//        }
    }
}
